import os
import shutil


images_folder = "C:\\Users\\Administrator\\Desktop\\shuju\\zhw\\images"
labels_folder = "C:\\Users\\Administrator\\Desktop\\shuju\\zhw\\labels"
target_images_folder = "C:\\Users\\Administrator\\Desktop\\shuju\\dataset\\images"
target_labels_folder = "C:\\Users\\Administrator\\Desktop\\shuju\\dataset\\labels"

os.makedirs(target_images_folder, exist_ok=True)
os.makedirs(target_labels_folder, exist_ok=True)

image_files = sorted([os.path.splitext(file)[0] for file in os.listdir(images_folder) if file.endswith(".jpg")])
label_files = sorted([os.path.splitext(file)[0] for file in os.listdir(labels_folder) if file.endswith(".txt")])

if len(image_files) != len(label_files):
    print(len(image_files))
    print(len(label_files))
    print("Error: Number of images does not match number of labels.")
    exit()

existing_files = [file for file in os.listdir(target_images_folder) if file.endswith(".jpg")]
if existing_files:
    max_num = max([int(file.split('.')[0]) for file in existing_files])
else:
    max_num = 0


for i, (image_file, label_file) in enumerate(zip(image_files, label_files), start=max_num+1):
    new_image_name = f"{i}.jpg"
    new_label_name = f"{i}.txt"
    
    shutil.copyfile(os.path.join(images_folder, image_file + ".jpg"), os.path.join(target_images_folder, new_image_name))

    shutil.copyfile(os.path.join(labels_folder, label_file + ".txt"), os.path.join(target_labels_folder, new_label_name))

    print(f"Copied {image_file}.jpg to {new_image_name} and {label_file}.txt to {new_label_name}")
